/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//观察着聚类抽象类，保存所有观察在对象的引用，抽象类提高一个对观察着添加删除的方法
function absSubject(){
	//定义一个对象列表
	this.obServers = new Array();
}

//增加观察者
absSubject.prototype.attach = function(observers){
	var length = observers.length;
	for(var i=0; i<length; i++){
		alert('我监听了' + observers[i].name + '对象');
		this.obServers.push(observers[i]);
	}
}

//移除观察者
absSubject.prototype.detach = function(observerName){
	var index = 0;
	for(i in this.obServers){
		if(this.obServers[i].name != observerName){
			index = i;
		}
	}
	if(index > 0){
		this.obServers = this.obServers.slice(0, index).concat(this.obServers.slice(index + 1, this.obServers.length));
	}
}

//通知
//obname 变化的对象名称
//operation	操作
//操作数据索引
absSubject.prototype.notify = function(obname, indexs){
	var datas = new Array();
	var len = this.obServers.length;
	var k;
	for(var i=0; i<len; i++){
		if(this.obServers[i].name == obname){
			for(j=0; j<indexs.length; j++){
				datas[j] = this.obServers[i].datas[indexs[j]];
			}
			k = i;
			break;
		}
	}

	if(datas.length < 1) return;

	for(var i=0; i<len; i++){
		if(i == k){
			this.obServers[i].del(indexs);
		}else{
			this.obServers[i].add(datas);
		}
	}
}

//具体观察着聚焦类实现
function subject(){
	this.state = 1;
}

subject.prototype = new absSubject();

//观察者类
function abObServer(name){
	this.name = name;
	this.datas = new Array();
}

//添加数据
abObServer.prototype.add = function(datas){
	var length = datas.length;
	for(i=0; i<length; i++){
		this.datas.push(datas[i]);
	}

}

//删除数据
abObServer.prototype.del = function(indexs){
	//this.data[index].flag = false;
	var length	= indexs.length;
	var length1	= this.datas.length;
	var datas = new Array();
	for(i=0,k=0; i<length1; i++){
		for(j=0,h=0; j<length; j++){
			if(i == indexs[j]){
				h = 1;
			}
		}
		if(h == 0){
			datas[k] = this.datas[i];
			k++;
		}
	}
	this.datas = datas;
}

//绑定数据,注数据格式为一维的json数据格式
abObServer.prototype.bind = function(datas){
	var _len = datas.length;
	for(i=0; i<_len; i++){
		this.datas[i] = datas[i].name
	}
}

//数据源
var data = [{
	"name":"a"
},{
	"name":"b"
},{
	"name":"c"
},{
	"name":"d"
},{
	"name":"e"
},{
	"name":"f"
},{
	"name":"g"
}];

//行数据对象
var _obj = new subject();

var _ob1 = new abObServer('observer_1');
var _ob2 = new abObServer('observer_2');

_obj.attach(new Array(_ob1, _ob2));
_ob1.bind(data);
_obj.notify('observer_1', new Array(1,6));

for(i=0;i<_ob1.datas.length;i++){
	alert(_ob1.datas[i]);
}

for(i=0;i<_ob2.datas.length;i++){
	alert(_ob2.datas[i]);
}
